
%for a giving lambda, solve  optimal policy and calculate cost dist
function Cost_dist=  calc_cost_dist(CostBase, Sunit_guess,Scost_guess,Skwh_guess,  params, A_t, Nbar_i, HH_bin, CollPerc_t, Pol_t, Own_t, Inc_t, ...
 P_state, P_sale_state, PIns_state,PIns0_state, nat_level, lambda, min_damages, net_cost, dW_ds_tol, ...
    Load, RenProd, PPRegion, PPRegion2, PPInt, PPCap, PPInf,PPRandStacked, ...
 ProdMedian,DamagesCoef1,DamagesCoef2, DamagesCoefPoll1,DamagesCoefPoll2, TractSunlightProfile)


%dW_ds_tol=dW_ds_tol*10;

    [Sunit_opt, Skwh_opt, Scost_opt]=solve_S2(Sunit_guess,Scost_guess,Skwh_guess,  params, A_t, Nbar_i, HH_bin, CollPerc_t, Pol_t, Own_t, Inc_t, ...
 P_state, P_sale_state, PIns_state,PIns0_state, nat_level, lambda, min_damages, net_cost, dW_ds_tol, ...
    Load, RenProd, PPRegion, PPRegion2, PPInt, PPCap, PPInf,PPRandStacked, ...
 ProdMedian,DamagesCoef1,DamagesCoef2, DamagesCoefPoll1,DamagesCoefPoll2, TractSunlightProfile);


   

      %Simulate given optimal policy
%      [M_opt,BI_opt, D_opt, M_bin_opt, pi_bin_opt, Exp_sub_opt]=simulate(params, A_t, Nbar_i, HH_bin, CollPerc_t, Pol_t, Own_t, ...
%        Sunit_opt, Skwh_opt, Scost_opt, P_state, P_sale_state, PIns_state, PIns0_state);
run_damages=0;   

if net_cost==1
    run_damages=1;
end

        [M_opt,BI_opt, D_opt, DPol_opt, MargDamagesHour_opt, M_bin_opt, pi_bin_opt, Exp_sub_opt]=...
        simulate(params, A_t, Nbar_i, HH_bin, CollPerc_t, Pol_t, Own_t, Inc_t, ...
    Sunit_opt, Skwh_opt, Scost_opt, P_state, P_sale_state, PIns_state,PIns0_state, ...
    Load, RenProd, PPRegion, PPRegion2, PPInt, PPCap, PPInf,PPRandStacked, ...
 ProdMedian,DamagesCoef1,DamagesCoef2, DamagesCoefPoll1,DamagesCoefPoll2, TractSunlightProfile, run_damages);

CostOpt=sum(Exp_sub_opt);

if net_cost==1
    CostOpt=CostOpt+D_opt;
end

CostOpt
CostBase
lambda

Cost_dist=(CostOpt-CostBase).*(CostOpt-CostBase);